import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/home_business/search_page/widget/topic_item.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';
import 'package:xvideos/hj_utils/api_service/search_service.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

enum ChoseTopicEntry {
  home(false, '选择标签'),
  squire(false, '选择话题');

  final bool isGridStyle;
  final String title;

  const ChoseTopicEntry(this.isGridStyle, this.title);
}

class ChoseTopicPage extends StatefulWidget {
  static const String routeName = '/chose/tag';

  const ChoseTopicPage({super.key, this.entry, this.selectTags});

  final ChoseTopicEntry? entry;
  final List<TagsBean>? selectTags;

  @override
  State<ChoseTopicPage> createState() => _ChoseTopicPageState();
}

class _ChoseTopicPageState extends State<ChoseTopicPage> {
  late ChoseTopicEntry entry;
  final dataSource = <TagsBean>[];
  late RxList<TagsBean> selectTags;
  RefreshController? refreshController;
  int page = 1;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    entry = widget.entry ?? ChoseTopicEntry.home;
    selectTags = (widget.selectTags ?? []).obs;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      isLoading = false;
      if (entry != ChoseTopicEntry.home) {
        await fetchHomePublishTags();
      } else {
        await fetchHomePublishTags();
      }
      setState(() {});
    });
  }

  Future<List<TagsBean>?> fetchHomePublishTags() async {
    final res = await SearchService.fetchPublishTags();
    refreshController?.loadNoData();
    dataSource.addAll(res);
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(entry.title),
        // leading: InkWell(
        //   onTap: () {
        //     Get.back();
        //   },
        //   child: Icon(Icons.close, color: Colors.white, size: 18),
        // ),
        actions: [
          // Text(
          //   '${selectTags.isNotEmpty ? 1 : 0}/1',
          //   style: TextStyle(
          //     fontSize: 14.sp,
          //     color: Color(0xff666666),
          //   ),
          // ),
          // 16.sizeBoxW,
        ],
      ),
      body: pullYsRefresh(
        child: () {
          if (isLoading) return LoadingCenterWidget();
          if (dataSource.isEmpty) return CErrorWidget();

          if (entry.isGridStyle)
            return GridView.builder(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, mainAxisSpacing: 12, crossAxisSpacing: 9, childAspectRatio: 79 / 34),
              itemCount: dataSource.length,
              itemBuilder: (BuildContext context, int index) {
                return Obx(() {
                  final model = dataSource[index];
                  final select = selectTags.indexWhere((e) => e.id == model.id) != -1;
                  return GestureDetector(
                    onTap: () {
                      if (!select) {
                        selectTags.add(model);
                      } else {
                        selectTags.removeWhere((e) => model.id == e.id);
                      }
                    },
                    child: Stack(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(.05),
                            borderRadius: BorderRadius.circular(3),
                            border: select ? Border.all(width: 1, color: Color(0xffF68216)) : null,
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            model.name ?? '',
                            style: TextStyle(fontSize: 12, color: Colors.white),
                          ),
                        ),
                        if (select)
                          Positioned(
                            child: Image.asset(
                              'tag_select.png'.homePath,
                              width: 18,
                              height: 18,
                            ),
                            right: 0,
                            bottom: 0,
                          )
                      ],
                    ),
                  );
                });
              },
            );
          return ListView.separated(
            padding: EdgeInsets.only(left: 18.w, right: 18.w, top: 14.h),
            separatorBuilder: (_, __) => 14.h.sizeBoxH,
            itemCount: dataSource.length,
            itemBuilder: (BuildContext context, int index) {
              final model = dataSource[index];
              final select = selectTags.indexWhere((e) => e.id == model.id) != -1;
              return TopicItem(
                model: model,
                isSelect: select,
                onTap: () {
                  if (select) return;
                  selectTags.clear();
                  selectTags.add(model);
                  Get.back(result: model);
                },
              );
            },
          );
        }(),
        onInit: (ctr) => refreshController = ctr,
      ),
    );
  }
}
